from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from api.models import WechatUser
from api.utils.jwt_utils import verify_token
from api.utils.response import success_response, error_response
from adminapi.utils.log_utils import log_operation
from api.utils.pagination import paginate_queryset
from django.contrib.auth.models import User
import json
from django.utils import timezone
from django.core.paginator import Paginator

@csrf_exempt
@require_http_methods(['GET'])
def wechat_user_list(request):
    """
    获取微信用户列表
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    # 获取查询参数
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', 10))
    keyword = request.GET.get('keyword', '')

    # 构建查询
    queryset = WechatUser.objects.all()
    
    if keyword:
        queryset = queryset.filter(nickname__icontains=keyword)

    # 分页
    paginator = Paginator(queryset, page_size)
    records = paginator.get_page(page)
    
    # 准备返回数据
    data = {
        'total': paginator.count,
        'total_pages': paginator.num_pages,
        'current_page': page,
        'page_size': page_size,
        'items': []
    }
    
    # 处理每条记录
    for record in records:
        record_data = {
            'id': record.id,
            'nickname': record.nickname,
            'avatar': record.avatar,
            'gender': record.gender,
            'country': record.country,
            'province': record.province,
            'city': record.city,
            'created_at': timezone.localtime(record.created_at).strftime('%Y-%m-%d %H:%M:%S') if record.created_at else None,
            'updated_at': timezone.localtime(record.updated_at).strftime('%Y-%m-%d %H:%M:%S') if record.updated_at else None,
        }
        data['items'].append(record_data)
    user = WechatUser.objects.get(id=1)
    # 记录操作日志
    # log_operation(admin_id, 'wechat_user_list', f'查看微信用户列表')
    log_operation(
        admin_id=admin_id,
        action='change',
        message=f'获取微信用户信息列表',
        
    )

    return success_response(data)

@csrf_exempt
@require_http_methods(['GET'])
def wechat_user_detail(request, user_id):
    """
    获取微信用户详情
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        user = WechatUser.objects.get(id=user_id)
        data = user.to_dict()
        
        # 记录操作日志
        log_operation(admin_id, 'wechat_user_detail', f"查看微信用户详情 ID:{user_id}")

        return success_response(data)
    except WechatUser.DoesNotExist:
        return error_response('用户不存在', code=404)

@csrf_exempt
@require_http_methods(['PUT'])
def wechat_user_update(request, user_id):
    """
    更新微信用户信息
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        user = WechatUser.objects.get(id=user_id)
        data = json.loads(request.body)
        
        # 更新字段
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'avatar' in data:
            user.avatar = data['avatar']
        if 'gender' in data:
            user.gender = data['gender']
        if 'country' in data:
            user.country = data['country']
        if 'province' in data:
            user.province = data['province']
        if 'city' in data:
            user.city = data['city']
        
        user.save()
        
        # 记录操作日志
        # log_operation (admin_id, 'update_wechat_user', f"更新微信用户信息 ID:{user_id}")
        log_operation(
            admin_id=admin_id,
            action='change',
            message=f"更新微信用户信息 ID:{user_id}",
        )

        return success_response(message='更新成功')
    except WechatUser.DoesNotExist:
        return error_response('用户不存在', code=404)
    except json.JSONDecodeError:
        return error_response('无效的请求数据', code=400)

@csrf_exempt
@require_http_methods(['DELETE'])
def wechat_user_delete(request, user_id):
    """
    删除微信用户
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        user = WechatUser.objects.get(id=user_id)
        user.delete()
        
        # 记录操作日志
        # log_operation(admin_id, 'delete_wechat_user', f"删除微信用户 ID:{user_id}")
        log_operation(
            admin_id=admin_id,
            action='delete',
            message=f"删除微信用户 ID:{user_id}",
        )


        return success_response(message='删除成功')
    except WechatUser.DoesNotExist:
        return error_response('用户不存在', code=404) 